package com.baseLesson._03_io.pritice;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;

public class ByteStreamDemo {

    public static void write() {

        //1.构建要写的文件对象
        File file = new File("data/test/first.txt");
        try {
            //2.构建文件输出流对象(构造时定义为追加内容)
            OutputStream outputStream = new FileOutputStream(file,true);
            //3.定义输出内容
            String content = "第一次a";
            //4.把内容写入文件
            outputStream.write(content.getBytes());
            //5.关闭输出流
            outputStream.close();
            System.out.println("写入内容成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    public static void read() {
        //1.构建要写的文件对象
        File file = new File("data/test/first.txt");
        //2.构建文件【输入】流对象
        try {
            InputStream fileInputStream = new FileInputStream(file);
            //3.读取内容
            //创建一辆小车
            byte[] byteArray = new byte[3];
            //当文件没有被读取完时，一直按照byte数组的容量读取文件；
            while(fileInputStream.read(byteArray)!=-1) {
                System.out.println(new String(byteArray));
            }
            //5.关闭输出流
            fileInputStream.close();
            System.out.println("读取内容成功！！！");




        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        //演示字节打印案例
		String content1 = "我";
		String content2 = "1";
		String content3 = "g";


		System.out.println(Arrays.toString(content1.getBytes()));
        System.out.println(Arrays.toString(content1.getBytes("gbk")));
		System.out.println(Arrays.toString(content2.getBytes()));
		System.out.println(Arrays.toString(content3.getBytes()));

		//汉子 我 的字节数组
		byte[] bytes= {-26, -120, -111};
        try {
            System.out.println(new String(bytes,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //write();
        //read();
    }

}
